﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace MiniChat
{
   public static class Client
    {
        static Queue<DownloadTask> listdownload = new Queue<DownloadTask>();
        public static void ProcessMessage(string message, Socket sock,ref bool Logged)
        {
            message = Ullity.Trim(message);
            var arr_msg = message.Split(':');
            switch (arr_msg[0])
            {
                case ("loginstatus"):
                    if (arr_msg.Length == 2) {
                        if (arr_msg[1] == "True")
                        {
                            Logged = true;
                        }
                        else {
                            Logged = false;
                        }
                    }
                    break;
                case("PING"):
                    if (arr_msg.Length == 2) { Send("REPING:" + arr_msg[1], sock); }
                    break;
                case("info"):
                    if (arr_msg.Length == 2) {
                        var sdata =Ullity.Split(arr_msg[1],",");
                        foreach (string s in sdata)
                        {
                            if (s.Contains("http_avatar=")) {
                                CGlobalVariable.HttpImageServer = "http://" + s.Replace("http_avatar=","");
                            }
                            else if (s.Contains("http_server="))
                            {
                                CGlobalVariable.HttpImageServer = "http://" + s.Replace("http_server=", "");
                            }else if(s.Contains("fullname=")){
                                CGlobalVariable.FullName = s.Replace("fullname=", "");
                                CGlobalVariable.txtName.Dispatcher.Invoke(new Action(
                                    ()=>{
                                        CGlobalVariable.txtName.Text = CGlobalVariable.FullName;
                                        }
                                    ));
                            }
                            else if (s.Contains("statustext="))
                            {
                                CGlobalVariable.txtStatustext.Dispatcher.Invoke(
                                        new Action(() => {
                                            CGlobalVariable.txtStatustext.Text = s.Replace("statustext=", ""); ;
                                        })
                                    );
                            }
                            else if (s.Contains("useravatar="))
                            {
                                CGlobalVariable.UserAvatar = s.Replace("useravatar=", "");
                                DownloadTask dl = new DownloadTask()
                                {
                                    url = CGlobalVariable.HttpImageServer + CGlobalVariable.UserAvatar + ".jpg",
                                    username = CGlobalVariable.UserName
                                };
                                dl.action = new System.Threading.Tasks.Task(
                                    new Action(() =>
                                    {
                                        CGlobalVariable.imgUserAvatar.Dispatcher.Invoke(
                                                new Action(() =>
                                                {
                                                    try
                                                    {
                                                        BitmapImage bmi = new BitmapImage(new Uri(Path.Combine(CGlobalVariable.ImagePath, CGlobalVariable.UserName + ".jpg"), UriKind.Absolute));
                                                        CGlobalVariable.imgUserAvatar.Source = bmi;
                                                    }
                                                    catch {
                                                        Ullity.Log("Can't load avatar " + Path.Combine(CGlobalVariable.ImagePath, CGlobalVariable.UserName + ".jpg"), 3);
                                                    }
                                                })
                                            );
                                    })
                                    );
                                listdownload.Enqueue(dl);
                                download();
                            }
                        }
                    }
                    break;
                case("adduserstatus"):
                    if (arr_msg.Length == 2) {
                        if (arr_msg[1] == "True")
                        {
                            MessageBox.Show("Thêm bạn mới thành công !");
                        }
                        else {
                            MessageBox.Show("Thêm bạn mới thất bại !");
                        }
                    }
                    break;
                case ("updateuser"):
                    if (arr_msg.Length == 2)
                    {
                        var arrcontact = arr_msg[1].Split('|');
                        ContactItem ci = new ContactItem()
                        {
                            ContactName = arrcontact[0],
                            ContactFullName = arrcontact[1],
                            ContactImage = arrcontact[2],
                            ContastStatus = int.Parse(arrcontact[3])
                        };
                        CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                                     () => {
                                         
                                         for (int i = 0; i < CGlobalVariable.lsbContacts.Items.Count; i++) {
                                             ContactItem ct = (ContactItem)((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Tag;
                                             if (ct.ContactName == ci.ContactName) {
                                                 SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                                 if (ci.ContastStatus == 1)
                                                 {
                                                     sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                                 }
                                                 ((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Background = sbr;
                                                 
                                             }
                                         }
                                         
                                         }
                                     
                                     ));
                    }
                    break;
                case ("friendlist"):
                    if (arr_msg.Length == 2)
                    {
                        string listuser = arr_msg[1];
                        if (listuser == null) { return; }                      
                        var arrls = Ullity.Split(listuser,",");
                        foreach (string u in arrls)
                        {
                            if (u != "") {
                                //for(int ia =0 ;ia <100;ia++){
                                var arrcontact = u.Split('|');
                                ContactItem ci = new ContactItem() { 
                                    ContactName = arrcontact[0],
                                    ContactFullName = arrcontact[1],
                                    ContactImage = arrcontact[2],
                                    ContastStatus = int.Parse(arrcontact[3])
                                };
                                int itemindex = 0;
                                CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                                    () => {
                                        SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                        if (ci.ContastStatus == 1) {
                                            sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                        }
                                        
                                        StackPanel lbst = new StackPanel()
                                        {
                                            Height=128,
                                            Width=128,
                                            Background = sbr,
                                            Margin = new Thickness(2),
                                            Tag = ci,
                                        };
                                        BitmapImage bm = new BitmapImage(new Uri("/Images/no_avatar.png",UriKind.Relative));
                                        Image i = new Image()
                                        {
                                            Height = 80,
                                            Width=80,
                                            VerticalAlignment  = System.Windows.VerticalAlignment.Center,
                                            Source = bm
                                        };
                                        TextBlock tbfname = new TextBlock() { 
                                            Text = ci.ContactFullName,
                                            FontSize = 22,
                                            TextAlignment = TextAlignment.Center
                                        };
                                        TextBlock tbname = new TextBlock()
                                        {
                                            Text = ci.ContactName,
                                            FontSize = 14,
                                            TextAlignment = TextAlignment.Center
                                        };
                                        lbst.Children.Add(i);
                                        lbst.Children.Add(tbfname);
                                        lbst.Children.Add(tbname);
                                       itemindex = CGlobalVariable.lsbContacts.Items.Add(lbst);
                                    }
                                    ));
                                DownloadTask dl = new DownloadTask()
                                {
                                    url = CGlobalVariable.HttpImageServer + ci.ContactImage + ".jpg",
                                    username = ci.ContactName                                  
                                };
                                dl.action = new Task(
                                        new Action(()=>{
                                            CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                                                () =>
                                                {
                                                    StackPanel ls = (StackPanel)CGlobalVariable.lsbContacts.Items[itemindex];
                                                    Image i = (Image)ls.Children[0];
                                                    if(File.Exists(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg"))){
                                                        BitmapImage bm = new BitmapImage(new Uri(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg"), UriKind.Absolute));
                                                        i.Source = bm;
                                                    }

                                                })
                                                );
                                          })
                                    );
                                listdownload.Enqueue(dl);
                                download();
                            //}
                            }
                        
                        }
                       
                    }
                    break;
                case("removefriend"):
                    
                        
                            CGlobalVariable.lsbContacts.Dispatcher.Invoke(
                                new Action(() => {
                                    for (int i = 0; i < CGlobalVariable.lsbContacts.Items.Count; i++)
                                     {
                       
                                    ContactItem ct = (ContactItem)((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Tag;
                                        if (ct.ContactName == arr_msg[1])
                                        {
                                            CGlobalVariable.lsbContacts.Items.RemoveAt(i);
                                            i = CGlobalVariable.lsbContacts.Items.Count;
                                        }  
                                     }
                                })
                                );
                        
                    
                    break;
                case ("showmsg"):
                    MessageBox.Show(arr_msg[1]);
                    CGlobalVariable.IsDisconnected = true;
                    return;
                case ("addfriend"):
                    if (arr_msg[1] != "")
                    {
                        //for(int ia =0 ;ia <100;ia++){
                        var arrcontact = arr_msg[1].Split('|');
                        ContactItem ci = new ContactItem()
                        {
                            ContactName = arrcontact[0],
                            ContactFullName = arrcontact[1],
                            ContactImage = arrcontact[2],
                            ContastStatus = int.Parse(arrcontact[3])
                        };
                        int itemindex = 0;
                        CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                            () =>
                            {
                                SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                if (ci.ContastStatus == 1)
                                {
                                    sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                }

                                StackPanel lbst = new StackPanel()
                                {
                                    Height = 128,
                                    Width = 128,
                                    Background = sbr,
                                    Margin = new Thickness(2),
                                    Tag = ci,
                                };
                                BitmapImage bm = new BitmapImage(new Uri("/Images/no_avatar.png", UriKind.Relative));
                                Image i = new Image()
                                {
                                    Height = 80,
                                    Width = 80,
                                    VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                    Source = bm
                                };
                                TextBlock tbfname = new TextBlock()
                                {
                                    Text = ci.ContactFullName,
                                    FontSize = 22,
                                    TextAlignment = TextAlignment.Center
                                };
                                TextBlock tbname = new TextBlock()
                                {
                                    Text = ci.ContactName,
                                    FontSize = 14,
                                    TextAlignment = TextAlignment.Center
                                };
                                lbst.Children.Add(i);
                                lbst.Children.Add(tbfname);
                                lbst.Children.Add(tbname);
                                itemindex = CGlobalVariable.lsbContacts.Items.Add(lbst);
                            }
                            ));
                        DownloadTask dl = new DownloadTask()
                        {
                            url = CGlobalVariable.HttpImageServer + ci.ContactImage + ".jpg",
                            username = ci.ContactName
                        };
                        dl.action = new Task(
                                new Action(() =>
                                {
                                    CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                                        () =>
                                        {
                                            StackPanel ls = (StackPanel)CGlobalVariable.lsbContacts.Items[itemindex];
                                            Image i = (Image)ls.Children[0];
                                            if (File.Exists(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg")))
                                            {
                                                BitmapImage bm = new BitmapImage(new Uri(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg"), UriKind.Absolute));
                                                i.Source = bm;
                                            }

                                        })
                                        );
                                })
                            );
                        listdownload.Enqueue(dl);
                        download();
                    }
                    break;
            }
            Ullity.Log(message);
        }
       
        public static void download()
        {
            if (listdownload.Count == 0) { return; }
            var dlt = listdownload.Dequeue();
            Console.WriteLine(CGlobalVariable.ImagePath);
            bool cached = CGlobalVariable._db.GetCache(dlt.username, dlt.url);
            if (!cached)
            {
                if (!Directory.Exists(CGlobalVariable.ImagePath)) { Directory.CreateDirectory(CGlobalVariable.ImagePath); }
                WebClient wc = new WebClient();
                try
                {
                    wc.DownloadFile(new Uri(dlt.url), Path.Combine(CGlobalVariable.ImagePath, CGlobalVariable.UserName + ".jpg"));
                }
                catch (Exception ex) {
                    Ullity.Log(ex.Message, 2);
                }
            }
            dlt.action.Start();
            if (listdownload.Count > 0) { download(); }
        }

        

        public static void Send(String text, Socket sock)
        {
            try
            {
                sock.Send(Encoding.UTF8.GetBytes(text + "\n"));
            }
            catch { CGlobalVariable.IsDisconnected = true; }
        }
    }
}
